/**
 * 铁路电子客票
 */
layui.define(['table', 'form', 'dropdown', 'util', 'common'], function (exports) {
    var $ = layui.$
        , admin = layui.admin
        , setter = layui.setter
        , view = layui.view
        , table = layui.table
        , form = layui.form
        , dropdown = layui.dropdown
        , upload = layui.upload
        , util = layui.util
        , element = layui.element
        , common = layui.common;

    //机票行程单
    setTimeout(function () {
        table.render({
            elem: '#LAY-queryinvoice-railwayticket-manage'
            , url: setter.baseConfig.apiHost + '/api/railwayticket/getpagingrailwaytickets'
            , toolbar: '#toolbarDemo'
            , defaultToolbar: []
            , where: { uploadTimeStart: $('#ID-laydate-start-date-railwayticket-list-uploadtime').val(), uploadTimeEnd: $('#ID-laydate-end-date-railwayticket-list-uploadtime').val() }
            , method: 'post'
            , contentType: "application/json"
            , headers: { //通过 request 头传递
                Authorization: 'Bearer ' + layui.data(setter.tableName)[setter.request.tokenName]
            }
            , parseData: function (res) { // res 即为原始返回的数据
                return {
                    "code": res.errorCode, // 解析接口状态
                    "msg": res.errorMessage, // 解析提示文本
                    "count": res.data.totalCount, // 解析数据长度
                    "data": res.data.entities // 解析数据列表
                };
            }
            , cols: [[
                { type: 'numbers', fixed: 'left' }
                , { field: 'id', title: 'Id', hide: true }
                , { field: 'uploadTime', title: '上传时间', minWidth: 180 }
                , { field: 'invoiceNumber', title: '发票号码', minWidth: 200, templet: '#ID-table-queryinvoice-railwayticket-templet-invoiceNumber' }
                , { field: 'issueDate', title: '开票日期', minWidth: 110 }
                , { field: 'billTypeName', title: '票据类型', width: 220, templet: '#LAY-queryinvoice-railwayticket-billTypeTpl' }
                , { field: 'departureStation', title: '出发车站', minWidth: 100 }
                , { field: 'destinationStation', title: '到达车站', minWidth: 100 }
                , { field: 'trainNumber', title: '车次', minWidth: 100 }
                , { field: 'departureTime', title: '出发时间', minWidth: 140 }
                , { field: 'carriage', title: '车厢', minWidth: 90 }
                , { field: 'seat', title: '座位', minWidth: 90 }
                , { field: 'seatLevelTypeName', title: '座席等级', minWidth: 100 }
                , { field: 'taxAmount', title: '税费', minWidth: 110 }
                , { field: 'taxRate', title: '税率', minWidth: 110 }
                , { field: 'totalExcludeTax', title: '不含税金额', minWidth: 110 }
                , { field: 'total', title: '票价', minWidth: 110 }
                , { field: 'passengerName', title: '乘车人', minWidth: 110 }
                , { field: 'idNumber', title: '身份证号', minWidth: 180 }
                , { field: 'eticketNumber', title: '电子客票号', minWidth: 240 }
                , { field: 'buyerName', title: '购方名称', minWidth: 250 }
                , { field: 'buyerId', title: '购方纳税人识别号', minWidth: 180 }
                , { field: 'fileName', title: '文件名称', minWidth: 400 }
                , { field: 'comment', title: '备注', minWidth: 200 }
                //, { title: '操作', width: 240, fixed: 'right', toolbar: '#table-useradmin-webuser' }
            ]]
            , page: true
            , limit: 20
            , limits: [10, 20, 30, 40, 50]
            , text: { none: '无数据' }
        });
    });
    
    // 工具栏事件
    table.on('toolbar(LAY-queryinvoice-railwayticket-manage)', function (obj) {
        var id = obj.config.id;
        var checkStatus = table.checkStatus(id);
        var othis = lay(this);
        switch (obj.event) {
            case 'export'://导出excel
                let formData = {
                    taskName: '导出铁路电子客票',
                    billType: '4',
                    invoiceNumber: $(':input[name=invoiceNumber]').val(),
                    issueDateStart: $('#ID-laydate-start-date-railwayticket-issuedate').val(),
                    issueDateEnd: $('#ID-laydate-end-date-railwayticket-issuedate').val(),
                    uploadTimeStart: $('#ID-laydate-start-date-railwayticket-list-uploadtime').val(),
                    uploadTimeEnd: $('#ID-laydate-end-date-railwayticket-list-uploadtime').val(),
                    comment: $(':input[name=comment]').val(),
                    fileName: $(':input[name=fileName]').val()
                };
                admin.popup({
                    title: '数据导出'
                    , area: ['80%', '85%']
                    , id: 'LAY-popup-queryinvoice-railwayticket-export'
                    , success: function (layero, index) {
                        view(this.id).render('queryinvoice/exportform', formData).done(function () {
                            form.render(null, 'layuiadmin-form-queryinvoice-export');

                            //开启提交
                            form.on('submit(LAY-queryinvoice-export-front-submit)', function (data) {
                                //debugger;
                                var field = data.field; //获取提交的字段

                                //获取选中行数据
                                let exportFields = [];
                                var checkStatus = table.checkStatus('LAY-queryinvoice-export-manage');
                                var checkDataArr = checkStatus.data;
                                for (var i = 0; i < checkDataArr.length; i++) {
                                    var checkData = checkDataArr[i];
                                    var exportField = {
                                        name: checkData.name,
                                        value: checkData.value
                                    };
                                    exportFields.push(exportField);
                                }

                                //添加选中行数据
                                field.exportField = exportFields;
                                
                                $.ajax({
                                    url: setter.baseConfig.apiHost + '/api/railwayticket/export' //实际使用请改成服务端真实接口
                                    , type: 'post'
                                    , contentType: "application/json"
                                    , data: JSON.stringify(field)
                                    , beforeSend: function (xhr) {
                                        xhr.setRequestHeader("Authorization", 'Bearer ' + layui.data(setter.tableName)[setter.request.tokenName]);
                                    }
                                    , success: function (res) {
                                        if (res.errorCode != '00000') {
                                            layer.msg(res.errorMessage, {
                                                offset: 'auto'
                                                , icon: 2
                                                , time: 3000
                                            });

                                            return false;
                                        }

                                        layer.alert('导出申请已提交，系统已启用离线导出模式，本次导出的数据将展示在【我的-我的下载】中，请注意查收！', {
                                            offset: 'auto'
                                            , icon: 1
                                        });

                                        layui.table.reload('LAY-queryinvoice-railwayticket-manage'); //重载表格
                                        layer.close(index); //执行关闭
                                    }
                                });
                            });

                            //取消
                            // 普通事件
                            //  2.9+ 版本可省略 attr 参数，默认读取 lay-on
                            util.on({
                                cancel: function () {
                                    console.log(this); // 当前触发事件的 DOM 元素
                                    //layer.msg('触发了事件 1');
                                    layer.close(index);
                                }
                            });

                            // table
                            table.render({
                                elem: '#LAY-queryinvoice-export-manage'
                                , url: setter.baseConfig.apiHost + '/api/railwayticket/getexportfields'
                                //, toolbar: '#toolbarDemo'
                                //, defaultToolbar: []
                                //, where: { billType: "1" }
                                , method: 'post'
                                , contentType: "application/json"
                                , headers: { //通过 request 头传递
                                    Authorization: 'Bearer ' + layui.data(setter.tableName)[setter.request.tokenName]
                                }
                                , parseData: function (res) { // res 即为原始返回的数据
                                    return {
                                        "code": res.errorCode, // 解析接口状态
                                        "msg": res.errorMessage, // 解析提示文本
                                        //"count": res.data.totalCount, // 解析数据长度
                                        "data": res.data // 解析数据列表
                                    };
                                }
                                , cols: [[
                                    { type: 'checkbox', fixed: 'left', LAY_CHECKED: true }
                                    , { type: 'numbers', fixed: 'left', title: '序号' }
                                    , { field: 'id', title: 'Id', hide: true }
                                    , { field: 'name', title: '字段名称' }
                                    , { field: 'value', title: '字段代码', hide: true }
                                    //, { title: '操作', width: 240, fixed: 'right', toolbar: '#table-useradmin-webuser' }
                                ]]
                                , page: false
                                , limit: 10
                                , limits: [10, 15, 20, 25, 30]
                                , text: { none: '无数据' }
                            });

                            // 行单击事件
                            table.on('row(LAY-queryinvoice-export-manage)', function (obj) {
                                var data = obj.data; // 得到当前行数据
                                var dataCache = obj.dataCache; // 得到当前行缓存数据，包含特定字段 --- 2.8.8+
                                var index = obj.index; // 得到当前行索引
                                var tr = obj.tr; // 得到当前行 <tr> 元素的 jQuery 对象
                                var options = obj.config; // 获取当前表格基础属性配置项
                                var e = obj.e; // 当前的 jQuery 事件对象 --- 2.9.14+
                                console.log('onrow', obj); // 查看返回对象的所有成员

                                // obj.del() // 删除当前行
                                // obj.update(fields, related);  // 修改行数据
                                //obj.setRowChecked(opts); // 设置行选中状态
                                //obj.tr.addClass('layui-this');

                                // 标注当前点击行的选中状态
                                obj.setRowChecked({
                                    type: 'checkbox' // radio 单选模式；checkbox 复选模式
                                });
                            });

                        });
                    }
                });
                break;
        };
    });

    //工具条
    table.on('tool(LAY-myinvoice-manage)', function (obj) {
        var data = obj.data;
        if (obj.event === 'del') {
            layer.prompt({
                formType: 1
                , title: '敏感操作，请验证口令'
            }, function (value, index) {
                layer.close(index);

                layer.confirm('真的删除行么', function (index) {
                    obj.del();
                    layer.close(index);
                });
            });
        } else if (obj.event === 'edit') {
            admin.popup({
                title: '编辑用户'
                , area: ['500px', '450px']
                , id: 'LAY-popup-myinvoice-batchupload'
                , success: function (layero, index) {
                    view(this.id).render('user/user/userform', data).done(function () {
                        form.render(null, 'layuiadmin-form-useradmin');

                        //提交
                        form.on('submit(LAY-user-front-submit)', function (data) {
                            var field = data.field; //获取提交的字段

                            //提交 Ajax 成功后，关闭当前弹层并重载表格
                            $.ajax({
                                url: setter.baseConfig.apiHost + '/api/user/update' //实际使用请改成服务端真实接口
                                , type: 'post'
                                , contentType: "application/json"
                                , data: JSON.stringify(field)
                                , beforeSend: function (xhr) {
                                    xhr.setRequestHeader("Authorization", 'Bearer ' + layui.data(setter.tableName)[setter.request.tokenName]);
                                }
                                , success: function (res) {
                                    if (res.errorCode != '00000') {
                                        layer.msg(res.errorMessage, {
                                            offset: '15px'
                                            , icon: 2
                                            , time: 3000
                                        });

                                        return false;
                                    }

                                    //登入成功的提示与跳转
                                    layer.msg('修改成功', {
                                        offset: '15px'
                                        , icon: 1
                                        , time: 3000
                                    });

                                    layui.table.reload('LAY-myinvoice-manage'); //重载表格
                                    layer.close(index); //执行关闭
                                }
                            });
                        });
                    });
                }
            });
        } else if (obj.event === 'disable') {
            layer.confirm('确定要禁用吗？', function (index) {
                //提交 Ajax 成功后，关闭当前弹层并重载表格
                $.ajax({
                    url: setter.baseConfig.apiHost + '/api/user/disableuser' //实际使用请改成服务端真实接口
                    , type: 'post'
                    , contentType: "application/json"
                    , data: JSON.stringify({
                        id: data.id,
                        isEnabled: 'N'
                    })
                    , beforeSend: function (xhr) {
                        xhr.setRequestHeader("Authorization", 'Bearer ' + layui.data(setter.tableName)[setter.request.tokenName]);
                    }
                    , success: function (res) {
                        if (res.errorCode != '00000') {
                            layer.msg(res.errorMessage, {
                                offset: '15px'
                                , icon: 2
                                , time: 3000
                            });

                            return false;
                        }

                        //登入成功的提示与跳转
                        layer.msg('禁用成功!', {
                            offset: '15px'
                            , icon: 1
                            , time: 3000
                        });

                        layui.table.reload('LAY-myinvoice-manage'); //重载表格
                        layer.close(index); //执行关闭
                    }
                });
            });
        } else if (obj.event === 'enable') {
            layer.confirm('确定要启用吗？', function (index) {
                //提交 Ajax 成功后，关闭当前弹层并重载表格
                $.ajax({
                    url: setter.baseConfig.apiHost + '/api/user/disableuser' //实际使用请改成服务端真实接口
                    , type: 'post'
                    , contentType: "application/json"
                    , data: JSON.stringify({
                        id: data.id,
                        isEnabled: 'Y'
                    })
                    , beforeSend: function (xhr) {
                        xhr.setRequestHeader("Authorization", 'Bearer ' + layui.data(setter.tableName)[setter.request.tokenName]);
                    }
                    , success: function (res) {
                        if (res.errorCode != '00000') {
                            layer.msg(res.errorMessage, {
                                offset: '15px'
                                , icon: 2
                                , time: 3000
                            });

                            return false;
                        }

                        //登入成功的提示与跳转
                        layer.msg('启用成功!', {
                            offset: '15px'
                            , icon: 1
                            , time: 3000
                        });

                        layui.table.reload('LAY-myinvoice-manage'); //重载表格
                        layer.close(index); //执行关闭
                    }
                });
            });
        }
    });

    // 行单击事件
    table.on('row(LAY-queryinvoice-railwayticket-manage)', function (obj) {
        var data = obj.data; // 得到当前行数据
        var dataCache = obj.dataCache; // 得到当前行缓存数据，包含特定字段 --- 2.8.8+
        var index = obj.index; // 得到当前行索引
        var tr = obj.tr; // 得到当前行 <tr> 元素的 jQuery 对象
        var options = obj.config; // 获取当前表格基础属性配置项
        var e = obj.e; // 当前的 jQuery 事件对象 --- 2.9.14+

        var isInvoiceNumberCol = e.target.classList.contains('billtong-myinvoice-table-invoicenumber');
        if (!isInvoiceNumberCol) {
            console.log('非发票号码列，阻止row事件.');
            return false;
        }
        console.log('onrow', data); // 查看返回对象的所有成员
        // obj.del() // 删除当前行
        // obj.update(fields, related);  // 修改行数据
        // obj.setRowChecked(opts); // 设置行选中状态

        //适配发票预览，先调用获取发票详情接口获取发票详情，然后打开预览窗口
        let request = {
            myInvoiceId: data.myInvoiceId,
            billType: data.billType,
            invoiceNumber: data.invoiceNumber
        };
        common.doOpen(request);
    });

    //管理员管理
    table.render({
        elem: '#LAY-user-back-manage'
        , url: './res/json/useradmin/mangadmin.js' //模拟接口
        , cols: [[
            { type: 'checkbox', fixed: 'left' }
            , { field: 'id', width: 80, title: 'ID', sort: true }
            , { field: 'loginname', title: '登录名' }
            , { field: 'telphone', title: '手机' }
            , { field: 'email', title: '邮箱' }
            , { field: 'role', title: '角色' }
            , { field: 'jointime', title: '加入时间', sort: true }
            , { field: 'check', title: '审核状态', templet: '#buttonTpl', minWidth: 80, align: 'center' }
            , { title: '操作', width: 150, align: 'center', fixed: 'right', toolbar: '#table-useradmin-admin' }
        ]]
        , text: '对不起，加载出现异常！'
    });

    //工具条
    table.on('tool(LAY-user-back-manage)', function (obj) {
        var data = obj.data;
        if (obj.event === 'del') {
            layer.prompt({
                formType: 1
                , title: '敏感操作，请验证口令'
            }, function (value, index) {
                layer.close(index);
                layer.confirm('确定删除此管理员？', function (index) {
                    console.log(obj)
                    obj.del();
                    layer.close(index);
                });
            });
        } else if (obj.event === 'edit') {
            admin.popup({
                title: '编辑管理员'
                , area: ['420px', '450px']
                , id: 'LAY-popup-myinvoice-batchupload'
                , success: function (layero, index) {
                    view(this.id).render('user/administrators/adminform', data).done(function () {
                        form.render(null, 'layuiadmin-form-admin');

                        //提交
                        form.on('submit(LAY-user-back-submit)', function (data) {
                            var field = data.field; //获取提交的字段

                            //提交 Ajax 成功后，关闭当前弹层并重载表格
                            //$.ajax({});
                            layui.table.reload('LAY-user-back-manage'); //重载表格
                            layer.close(index); //执行关闭 
                        });
                    });
                }
            });
        }
    });

    //角色管理
    table.render({
        elem: '#LAY-user-back-role'
        , url: './res/json/useradmin/role.js' //模拟接口
        , cols: [[
            { type: 'checkbox', fixed: 'left' }
            , { field: 'id', width: 80, title: 'ID', sort: true }
            , { field: 'rolename', title: '角色名' }
            , { field: 'limits', title: '拥有权限' }
            , { field: 'descr', title: '具体描述' }
            , { title: '操作', width: 150, align: 'center', fixed: 'right', toolbar: '#table-useradmin-admin' }
        ]]
        , text: '对不起，加载出现异常！'
    });

    //工具条
    table.on('tool(LAY-user-back-role)', function (obj) {
        var data = obj.data;
        if (obj.event === 'del') {
            layer.confirm('确定删除此角色？', function (index) {
                obj.del();
                layer.close(index);
            });
        } else if (obj.event === 'edit') {
            admin.popup({
                title: '添加新角色'
                , area: ['500px', '480px']
                , id: 'LAY-popup-myinvoice-batchupload'
                , success: function (layero, index) {
                    view(this.id).render('user/administrators/roleform', data).done(function () {
                        form.render(null, 'layuiadmin-form-role');

                        //提交
                        form.on('submit(LAY-user-role-submit)', function (data) {
                            var field = data.field; //获取提交的字段

                            //提交 Ajax 成功后，关闭当前弹层并重载表格
                            //$.ajax({});
                            layui.table.reload('LAY-user-back-role'); //重载表格
                            layer.close(index); //执行关闭 
                        });
                    });
                }
            });
        }
    });

    exports('railwayticket', {})
});